package cn.ycl.syslog;


import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.ycl.auth.api.user.domain.User;
import cn.ycl.auth.api.user.feign.RemoteUserService;
import cn.ycl.entity.UserInfoVO;
import cn.ycl.system.api.syslog.domain.SysLog;
import cn.ycl.system.api.syslog.feign.RemoteSysLogService;

import cn.ycl.utils.HttpUtil;
import cn.ycl.utils.IPUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author YuanChangLiang
 * @description AOP日志实现
 * @date created in 15:30 2021/6/7
 */

@Aspect
@Slf4j
@Component
public class SysLogAspect {

    @Autowired
    private RemoteSysLogService remoteSysLogService;
    @Autowired
    private RemoteUserService remoteUserService;

    @Pointcut("@annotation(cn.ycl.syslog.SystemLog)")
    public void getSysLog() {
    }

    @Around(value = "getSysLog()")
    public Object operationLog(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long beginTime = System.currentTimeMillis();
        Object proceed = proceedingJoinPoint.proceed();
        long time = System.currentTimeMillis() - beginTime;
        //保存日志
        saveSysLog(proceedingJoinPoint, time);
        return proceed;
    }

    /**
     * 保存日志
     *
     * @param joinPoint
     * @param time
     */
    private void saveSysLog(ProceedingJoinPoint joinPoint, long time) {
        Object[] args = joinPoint.getArgs();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        SystemLog log = method.getAnnotation(SystemLog.class);
        //保存日志
        SysLog sysLog = new SysLog();
        HttpServletRequest request = HttpUtil.getHttpServletRequest();
        String ipAddress = IPUtil.getIpAddress(request);
        String address = HttpUtil.getAddressPlus(ipAddress);
        sysLog.setIp(address + ipAddress);
        sysLog.setMethod(method.getName());
        sysLog.setOperation(log.value());
        List<Object> paramsList = new ArrayList<Object>();
        for (Object arg : args) {
            if (!(arg instanceof HttpServletRequest)) {
                paramsList.add(arg);
            }

        }
        String contextPath = request.getRequestURI();
        //登录接口，且带参，且账号密码正确，则记录日志
        if ("/login/login".equals(contextPath) ) {
            if(paramsList.size() == 0){
               return;
            }
            Object o = paramsList.get(0);
            JSONObject entries = JSONUtil.parseObj(o);
            String userName = entries.get("userName").toString();
            String password = entries.get("password").toString();
            User user = remoteUserService.queryByUserName(userName);
            if (Objects.nonNull(user) && password.equals(user.getPassword())) {
                sysLog.setUserId(user.getUserId());
                sysLog.setUserName(userName);
            }else{
                return;
            }
        }else {
            UserInfoVO userInfo = remoteUserService.getUserInfo();
            if (Objects.isNull(userInfo)) {
                return;
            }else{
                sysLog.setUserName(userInfo.getUserName());
                sysLog.setUserId(userInfo.getUserId());
            }
        }
        sysLog.setParams(JSONUtil.toJsonStr(paramsList));
        sysLog.setTime(time);
        sysLog.setType(log.type().getCode());
        remoteSysLogService.insert(sysLog);
    }


}
